/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src;

import java.util.HashMap;
import java.util.Set;
import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Novo extends HttpServlet{
    
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        processar(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response){
        processar(request,response);
    }

    private void processar(HttpServletRequest request, HttpServletResponse response) {
       
        try{
			listaUsuarios listaObj = new listaUsuarios();
			HashMap<String, Usuario> listaUser = new HashMap<>();
			Usuario user = new Usuario();
			String url = null;
			
			//*****************Carrega do arquivo para sessão**********************
			HttpSession session = request.getSession();
            if(session.getAttribute("listaObj")==null){
                try {
					FileInputStream fis = new FileInputStream("usuarios.obj");
					ObjectInputStream ois = new ObjectInputStream(fis);
					listaObj = (listaUsuarios) ois.readObject();
					listaUser = listaObj.getListaUsuarios();
					session.setAttribute("listaObj", listaObj);
				} catch (Exception e) {
				}
			}else{
				listaObj = (listaUsuarios) session.getAttribute("listaObj");
				listaUser = listaObj.getListaUsuarios();
			}
			//*********************************************************************
		
			if(listaUser.containsKey(request.getParameter("email"))){
				url = "erro.jsp?erro=ERRO: Email ja cadastrado";
			}else{
				user.setNome(request.getParameter("nome"));
				user.setSobrenome(request.getParameter("sobrenome"));
				user.setEmail(request.getParameter("email"));
				user.setSenha(request.getParameter("senha"));
				
				listaUser.put(request.getParameter("email"), user);
				listaObj.setListaUsuarios(listaUser);
				session.setAttribute("listaObj", listaObj);
				
				url = "cadastrar.jsp";
				
				try {
					FileOutputStream file = new FileOutputStream("usuarios.obj");
					ObjectOutputStream oos = new ObjectOutputStream(file);
					oos.writeObject(listaObj);
					oos.close();
				} catch (Exception e) {
				}
			}
			
            RequestDispatcher dispatcher = request.getRequestDispatcher(url);
            dispatcher.forward(request, response);
            
        }catch(Exception e){
            e.printStackTrace();
		}
    }
}
